package gcb.metalsys.auth.face;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import gcb.metalsys.base.ResultUtil;
import gcb.metalsys.base.dto.ResultDTO;
import gcb.metalsys.service.auth.AuthUserService;
import gcb.metalsys.utils.GsonUtils;
import gcb.metalsys.utils.HttpUtil;
import lombok.Data;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.RequestBody;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ReMidDream
 * @date 2018-09-10 19:48
 **/
@Data
public class FaceAuthenticationProvider implements AuthenticationProvider {

    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        FaceAuthenticationToken authenticationToken = (FaceAuthenticationToken)authentication;
        String userName = (String)authenticationToken.getPrincipal();
        String imageUrl = (String)authenticationToken.getCredentials();

        String userId = authFaceSearch(imageUrl);
        if (userId != null) {
            UserDetails userDetails = userDetailsService.loadUserByUsername(userId);

            FaceAuthenticationToken authenticationResult = new FaceAuthenticationToken(userDetails,imageUrl, userDetails.getAuthorities());
            authenticationResult.setDetails(authenticationToken.getDetails());
            return authenticationResult;
        }else{
            throw new InternalAuthenticationServiceException("非本人,登录失败!");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return FaceAuthenticationToken.class.isAssignableFrom(authentication);
    }

    private String authFaceSearch(String imgBase64Url){
        //调用百度API
        String faceSearchResult = faceSearch(imgBase64Url);

        JSONObject resultJsonObject = JSONObject.parseObject(faceSearchResult);
        resultJsonObject = JSONObject.parseObject(resultJsonObject.get("result").toString());
        JSONArray userListJsonArray = JSONArray.parseArray(resultJsonObject.get("user_list").toString());
        //判断人脸识别分数
        if(Float.parseFloat(userListJsonArray.getJSONObject(0).get("score").toString())>80.00) {
            System.out.println("同一个人");
            return (String)userListJsonArray.getJSONObject(0).get("user_id");
        }
        return null;
    }

    private String faceSearch(String imageBase64Url) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", imageBase64Url);
            map.put("liveness_control", "NORMAL");
            map.put("group_id_list", "group_bank");
            map.put("image_type", "BASE64");
            map.put("quality_control", "LOW");

            String param = GsonUtils.toJson(map);

            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "24.5de09c86668572ad9d82ec586ab817fc.2592000.1597913242.282335-21513455";

            return HttpUtil.post(url, accessToken, "application/json", param);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String imageToBase64(String filePath) throws Exception{
        if(StringUtils.isBlank(filePath)){
            return null;
        }
        String encode="";
        try{
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
//            encode = Base64.encode(bytes);
            encode = Base64.encodeBase64String(bytes);
        }catch (Exception e){
            throw e;
        }
        return encode;
    }
}
